package cn.tedu.eguser1.controller;

import cn.tedu.eguser1.base.response.JsonResult;
import cn.tedu.eguser1.base.response.StatusCode;
import cn.tedu.eguser1.mapper.UserMapper;
import cn.tedu.eguser1.pojo.dto.UserAddParam;
import cn.tedu.eguser1.pojo.entity.User;
import cn.tedu.eguser1.pojo.vo.UserListVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/v1/user/")
@Tag(name="01-用户管理模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("add")
    @Operation(summary = "添加用户")
    @ApiOperationSupport(order = 10)
    public JsonResult addUser(@Valid @RequestBody UserAddParam userAddParam) {

        log.info("添加用户参数: {}", userAddParam);
        User user=new User();
        BeanUtils.copyProperties(userAddParam,user);
        user.setCreateTime(user.getCreateTime());
        user.setUpdateTime(user.getUpdateTime());
        int rows = userMapper.insertUser(user);
        if (rows > 0){
            return JsonResult.ok();
        } else {
            return new JsonResult(StatusCode.OPERATION_FILED);
        }
}
/**
 * 2.用户列表功能
 */
@GetMapping("list")
@Operation(summary = "查询用户列表")
@ApiOperationSupport(order = 20)
    public JsonResult list() {
    List<UserListVO> userListVOS =userMapper.selectUserList();
    return JsonResult.ok(userListVOS);
}
    /**
     * 3.删除用户功能;
     */
@PostMapping("del/{id}")
@Operation(summary = "删除用户")
@ApiOperationSupport(order = 30)
    public JsonResult deleteUser(@PathVariable  @Min(value = 1, message = "用户ID必须大于等于1")
                                 @Max(value = 100, message = "用户ID必须小于等于100" )Long id) {
    log.info("删除用户ID: {}", id);
    int rows = userMapper.deleteUserById(id);
    if (rows > 0){
        return JsonResult.ok();
    }else {
        return new JsonResult(StatusCode.OPERATION_FILED);
    }
}
    /**
     * 4.更新用户功能;
     */
    @PostMapping("update")
    @Operation(summary = "修改用户信息")
    @ApiOperationSupport(order = 40)
    public JsonResult updateUser(@RequestBody UserAddParam userAddParam) {
        System.out.println("userAddParam:"+userAddParam);
        User user=new User();
        BeanUtils.copyProperties(userAddParam,user);
        user.setUpdateTime(new Date());
        int rows=userMapper.updateUserById(user);
        if (rows > 0){
            return JsonResult.ok();
        }else {
            return new JsonResult(StatusCode.OPERATION_FILED);
        }
    }


}
